package com.rock.demo.auth.service;

import io.micrometer.core.instrument.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class RockUserDetailsServiceImpl implements UserDetailsService {

    private static List<User> userList;

    @Autowired
    public PasswordEncoder passwordEncoder;

    @PostConstruct
    public void initData(){
        userList = new ArrayList<>();
        userList.add(new User("rock",passwordEncoder.encode("123"), AuthorityUtils.commaSeparatedStringToAuthorityList("admin")));
        userList.add(new User("test", passwordEncoder.encode("123"), AuthorityUtils.commaSeparatedStringToAuthorityList("admin")));
    }

    //Security的登录，User赋予权限
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (StringUtils.isBlank(username)) {
            throw new UsernameNotFoundException("the username is not null");
        }

        //校验用户是否存在
        List<User> findUserList = userList.stream().filter(user -> user.getUsername().equals(username)).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(findUserList)){
            throw new UsernameNotFoundException("the user is not exist");
        }
        /**
        //给用户添加角色权限
        String role = user.getRole();
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority(role));
​
        //返回用户token
        return new org.springframework.security.core.userdetails.User(username, user.getOauthpassword(), authorities);
         **/
        return findUserList.get(0);
    }
}
